package lpc

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/c-bata/go-prompt"

	"gitee.com/dark.H/go-remote-repl/datas"
	"github.com/c-bata/go-prompt/completer"
)

var FilePathCompleter = completer.FilePathCompleter{
	IgnoreCase: true,
}

func FilePathInput() string {
	return prompt.Input("file choose >>", func(d prompt.Document) []prompt.Suggest {
		return FilePathCompleter.Complete(d)
	})
}

func GetAPISockFile() string {
	tmp := os.TempDir()
	return filepath.Join(tmp, "localCentry.sock")
	// return "localhost:65530"
}

func GetOwnPath() string {
	binFile := os.Args[0]

	if GOOS != "windows" {
		if !strings.HasPrefix(binFile, "/") {
			return filepath.Join(PWD, binFile)
		}
	}
	return binFile
}

func KillAPI() error {
	pid := GetPIDBYLocal()
	if GOOS == "windows" {
		cmd := exec.Command("cmd.exe", "/c", fmt.Sprintf("TASKKILL /PID %d", pid))
		return cmd.Run()
	} else {
		cmd := exec.Command("bash", "-c", fmt.Sprintf("kill -9 %d", pid))
		return cmd.Run()
	}
}

func GetPIDBYLocal() (pid int) {
	if IfLocalStart() {
		if con := SimpleClient(SOCK_FILE_PATH); con != nil {
			if datas.JsonSend(datas.Data{
				"Op": "pid",
			}, con) > 0 {
				data := datas.JsonRecv(con)
				if data["data"] != nil {
					pid = int(data["data"].(float64))

				}
				// fmt.Println((data))
				// fmt.Println("pid:", pid)
			}
		}

	}
	return
}

func IfLocalStart() (res bool) {
	var c net.Conn
	var err error
	if strings.HasPrefix(SOCK_FILE_PATH, "/") {
		c, err = net.Dial("unix", SOCK_FILE_PATH)
	} else {
		c, err = net.Dial("tcp", SOCK_FILE_PATH)
	}
	if err == nil {
		datas.JsonSend(datas.Data{"Op": "check"}, c)
		defer c.Close()
		res = true
		return
	}
	return
}

func IfOuterStart() (res bool) {
	c, err := net.Dial("tcp", "localhost:65531")

	if err == nil {

		datas.JsonSend(datas.Data{"Op": "pid"}, c)
		res = true
		defer c.Close()
	}
	return
}
